<template>
  <div class="login-container">
    <!-- <img width="100%" height="100%" src="/vendor/login_bg.jpg" style="position:absolute; left:0; top:0; z-index:-1;"/> -->
    <el-form class="login-form" :rules="loginRules" ref="loginForm" :model="loginInfo">
      <div v-loading='loading' :element-loading-text="$t('common.loggingIn')" element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255,0.5)">
        <div class="logo"></div>
      <el-form-item prop="username" class="login-control">
        <span class="icon-container" style="margin-top: -8px;">
          <i
            class="iconfont loginicon"
            :class="{
            'icon-renbudaiwaiquan':loginAuthmode==='database',
            'icon-orguser': loginAuthmode==='ldap' }"
          ></i>
        </span>
        <el-input
          type="text"
          v-model.trim="loginInfo.username"
          :placeholder="_('Username')"
          @keyup.native.enter="handleFormLogin('loginForm')"
          tabindex="3"
          name="login-username"
        ></el-input>
        <template v-if="features.enable_ldap">
          <el-dropdown @command="handleCommand" style="left: -3px">
            <span class="el-dropdown-link">
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown" class="loginicon">
              <el-dropdown-item
                command="database"
                :class="{'activeUserCategory':loginAuthmode==='database' }"
              >
                <i
                  class="categoryCheck"
                  :class="[loginAuthmode==='database' ? 'el-icon-check' : '']"
                ></i>
                {{ _('Local Account') }}
              </el-dropdown-item>
              <el-dropdown-item
                v-if="features.enable_ldap"
                command="ldap"
                :class="{'activeUserCategory' : loginAuthmode==='ldap'}"
              >
                <i class="categoryCheck" :class="{'el-icon-check' : loginAuthmode==='ldap'}"></i>
                {{ _('Domain Account') }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-form-item>
      <el-form-item prop="password" class="login-control">
        <span class="icon-container" style="margin-top: -4px;">
          <i class="iconfont icon-mima loginicon"></i>
        </span>
        <el-input
          :type="inputType"
          v-model="loginInfo.password"
          :placeholder="_('Password')"
          @keyup.native.enter="handleFormLogin('loginForm')"
          tabindex="4"
          name="login-password"
        ></el-input>
        <i
          class="iconfont password"
          @click.stop="changePasswordType()"
          :class="[inputType==='password' ? 'icon-mimakejian' : 'icon-mimabukejian']"
          style="margin-top: 4px;"
        ></i>
      </el-form-item>
      <el-checkbox style="color:#999999" v-model="rememberPw">{{$t('common.rememberPw')}}</el-checkbox>
      <el-form-item class="loginBtn login-control">
        <el-button
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleFormLogin('loginForm')"
          name="login-submit"
        >
          <i :class="{'el-icon-loading':loading}"></i>
          {{_('Login') }}
        </el-button>
      </el-form-item>
      <div style="overflow: hidden;line-height:23px;">
        <!-- <router-link :to="{ path:'/download'}" class="download">{{ _('Download Center')}}</router-link> -->
        <el-link class="download" :href="this.$url_prefix + '/op-help-center/doc/article/39711'" target="_blank" :underline="false">{{ _('Download Center')}}</el-link>
        <el-tooltip
          class="download"
          effect="dark"
          :content="loginInfo.authrole === 'system_admin' ? $t('common.systemAdminForgetPassword') : $t('common.tenantAdminForgetPassword') "
          placement="top-start"
        >
          <el-link :underline="false" class="forgetPassword">{{ _('Forget Password')}}</el-link>
        </el-tooltip>
        <lang-select class="lang"></lang-select>
      </div>
      </div>
    </el-form>
  </div>
</template>
<script>
import { getUserName, Authmode, decodeToken, encrypt } from "@/utils/auth";
import LangSelect from "./LangSelect";
import store from "@/store";
import lodash from "lodash";
export default {
  name: "login",
  components: { LangSelect },
  data() {
    var validateName = (rule, value, callback) => {
      if (value.slice(-5) === "@ldap") {
        callback(new Error(this._("Username cannot end with @ldap")));
      } else {
        callback();
      }
    };
    return {
      inputType: "password",
      loading: false,
      features: {
        enable_ldap: false
      },
      loginInfo: {
        username: "",
        password: "",
        authmode: Authmode.get() || "database",
        authrole: "tenant_admin"
      },
      loginRules: {
        username: [
          {
            required: true,
            message: this._("Please input username"),
            trigger: "blur"
          },
          { max: 32, message: this.$t('message.usernameLength'), trigger: 'blur' },
          { validator: validateName, trigger: "change, blur" }
        ],
        password: [
          {
            required: true,
            message: this._("Please input the password"),
            trigger: "blur"
          },
          { validator: (rule, value, callback) =>{  
            // 暂时不需要提示不许输入中文空格
            if (value) {    
              if (/[\u4e00-\u9fa5\s]$/ig.test(value)) {
                callback(new Error(this.$t('common.noZh')));
              } else {
                callback();
              }
            }
            callback();
          }, trigger: 'blur'},
          { max: 32, message: this.$t('message.passwordLength'), trigger: 'blur' }
        ]
      },
      loginAuthmode: Authmode.get() || "database",
      redirect: undefined,
      rememberPw: false
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.setAuthrole();
    })
  },
  beforeRouteUpdate() {
    this.setAuthrole();
  },
  mounted() {
    if (this.loginInfo.authrole === 'system_admin') {
      if(this.$cookies.get('isRememberPw_sys')) {
        this.loginInfo.username = decodeToken(this.$cookies.get('isRememberUn_sys'))
        this.loginInfo.password = decodeToken(this.$cookies.get('isRememberPw_sys'))
        this.rememberPw =  true;
      } else {
        this.rememberPw =  false;
      }
    }else {
      if(this.$cookies.get('isRememberPw_ten')) {
        this.loginInfo.username = decodeToken(this.$cookies.get('isRememberUn_ten'))
        this.loginInfo.password = decodeToken(this.$cookies.get('isRememberPw_ten'))
        this.rememberPw =  true;
      } else {
        this.rememberPw =  false;
      }
    }
  },
  methods: {
    setAuthrole() {
      if (this.$route.path.indexOf('system') !== -1) {
        this.loginInfo.authrole = 'system_admin';
      } else {
        this.loginInfo.authrole = 'tenant_admin';
      }
    },
    async handleFormLogin(formName) {
      const valid = await (this.$refs[formName]).validate();
      if (!valid) {
        return false;
      }

      this.loading = true;
      try {
        const loginParams = this.handleLoginInfo(this.loginInfo);
        await this.$store.dispatch("Login", loginParams);
        if (this.rememberPw) {
          if (this.loginInfo.authrole === 'system_admin') {
            this.$cookies.set('isRememberUn_sys', encrypt(this.loginInfo.username), 60 * 60 * 7)
            this.$cookies.set('isRememberPw_sys', encrypt(this.loginInfo.password), 60 * 60 * 7)
          }else {
            this.$cookies.set('isRememberUn_ten', encrypt(this.loginInfo.username), 60 * 60 * 7)
            this.$cookies.set('isRememberPw_ten', encrypt(this.loginInfo.password), 60 * 60 * 7)
          }
        } else {
          if (this.loginInfo.authrole === 'system_admin') {
            this.$cookies.remove('isRememberUn_sys');
            this.$cookies.remove('isRememberPw_sys');
          }else {
            this.$cookies.remove('isRememberUn_ten');
            this.$cookies.remove('isRememberPw_ten');
          }
        }
        this.$router.push({ path: '/overview' });
        this.loading = false;
      } catch (error) {
        // if (error.response && error.response.status === 401) {
        //   (this.$refs[formName]).fields[1].validateMessage = this.$t(
        //     "message.inputInvalid",
        //     {
        //       paramName:
        //         this.$t("login.userName").toString() +
        //         this.$t("common.or").toString() +
        //         this.$t("login.password").toString()
        //     }
        //   );
        // } else {
        //   (this.$refs[formName]).fields[1].validateMessage = this.$t(
        //     "message.failedToConnect",
        //     {
        //       objectName: this.$t("common.server")
        //     }
        //   );
        // }
        // (this.$refs[formName]).fields[1].validateState = "error";
        this.loading = false;
      }
    },

    handleLoginInfo(credentials) {
      const params = lodash.cloneDeep(credentials);
      if (this.loginAuthmode === "ldap") {
        params.username += "@ldap";
      }
      // params['password_certification'] = 'yes'
      return params;
    },
    changePasswordType() {
      if (this.inputType === "password") {
        this.inputType = "text";
      } else {
        this.inputType = "password";
      }
    },
    handleCommand(command) {
      this.loginAuthmode = command;
      this.loginInfo.authmode = command;
    }
  }
};
</script>
<style lang="scss" scoped>
.login-container {
  height: 100vh;
  background: url("/login_bg.jpg") no-repeat center;
  background-size: cover;

  .el-input {
    display: inline-block;
    width: 70%;

    ::v-deep input:-webkit-autofill {
      kit-box-shadow: 0 0 0px 1000px #fff inset !important;
      -webkit-text-fill-color: #666 !important;
    }

    ::v-deep input {
      border: 0px solid #dcdfe6;
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 0px 5px 0px 10px;
      color: #666;
      height: 30px;
    }
  }

  .login-form {
    background: url("/login_form_bg.png") 0 0 no-repeat;
    background-size: contain;
    position: absolute;
    width: 360px;
    height: 500px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    padding: 15px 55px;
    border-radius: 10px;

    & .logo {
      margin-top: 80px;
      margin-bottom: 40px;
      height: 80px;
      background: url("/icon.png") center no-repeat;
      background-size: contain;
      // background-size: contain;
    }
  }

  .el-form-item {
    border: 1px solid #ccc;
    border-radius: 20px;
    color: #454545;

    .el-form-item__content {
      line-height: 32px;
    }
  }

  .icon-container {
    padding: 0px 12px;
    color: #889aa4;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .iconfont {
    color: #889aa4;
    font-size: 20px;
  }

  .loginicon {
    color: #4fe2eb;
  }

  .password {
    color: #889aa4;
    cursor: pointer;
    position: absolute;
    right: 18px;
  }

  .loginBtn {
    border: none;
    margin-top: 15px;

    .el-button {
      padding: 10px 20px;
      border-radius: 20px;
      border: 1px transparent solid;
      background-size: 100%;
      position: relative;
    }

    .el-icon-loading {
      position: absolute;
      left: 80px;
      top: 14px;
    }
  }

  .download,
  .forgetPassword {
    font-size: 13px;
    color: #999;
    transition: all 0.3s linear;
  }

  .download:hover,
  .forgetPassword:hover {
    color: #666;
  }

  .forgetPassword {
    margin-left: 8px;
  }
}

.lang {
  float: right;
}

.login-container::v-deep .el-form-item__error {
  padding: 5px 0 0 15px;
}
</style>
<style lang="css">
.login-control {
  height: var(--login-control-height);
  line-height: var(--login-control-height);
}
.login-control .el-form-item__content {
  height: var(--login-control-height);
  line-height: var(--login-control-height);
}
</style>
